<?php

namespace App\Http\Controllers\backstage;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use App\Models\BackstageModel;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;

// require_once '../app/libary/captcha/Code.class.php';

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/backstage';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    // public function index(){
    //     // print_r(session('admin'));exit;
        
    //     $meun = LoginModel::getMeun(['pid'=>0]);

    //     return view('backstage/index',['meun'=>$meun]);
    // }
    
    public function login(){
        return view('backstage/index/login');
    }

    public function userLogin(){
        if( Input::all() ){
            $data = Input::all();
            $code = new Code;
            $_code =  $code->get();

            if( strtoupper( $data['code'] ) != $_code ){
                return response()->json(['res'=>'0','msg'=>'驗證碼輸入錯誤！請重新輸入驗證碼！']);
            }
            if( empty( $data['name'] ) || empty($data['password']) ){
                return response()->json(['res'=>'0','msg'=>'請輸入用戶名，或密碼！']);
            }
            $userInfo = BackstageModel::getOneAdmin(['user_name'=>$data['name']]);
            if(  $userInfo =='' ){
                return response()->json(['res'=>'0','msg'=>'賬號不存在，請重新輸入！']);
            }

            if( $userInfo->user_pass !=  md5(base64_encode(trim( $data['password'] )) ) ){
                return response()->json(['res'=>'0','msg'=>'用戶名或密碼輸入不正確，請重新輸入！']);
            }

            session(['admin'=>$userInfo]);
            // return redirect('backstage/index');
            return response()->json(['res'=>'1','msg'=>'登錄成功！']);
        }
        
    }


    public function code(){
       $code = new Code;
       $code -> make();
    }

    public function loginOut(Request $request){
        $request->session()->flush();
        $request->session()->regenerate();
        // session(['admin'=>null]);
        // echo '<script>top.location.href="https://'.$_SERVER['HTTP_HOST'].'/backstage/login";</script>';
        return redirect('backstage/login');
    }

}
